package com.mate.cloud.auth.filter;

import com.mate.cloud.auth.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 构建JWT验证过滤器
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2025/6/6 14:30
 * @updateUser: MI
 * @updateTime: 2025/6/6 14:30
 * @updateRemark: 修改内容
 * @version: 1.0
 */
@Slf4j
@Component
public class JwtFilter extends OncePerRequestFilter {


    @Resource
    UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwtToken = request.getHeader("token");//从请求头中获取token
        if (jwtToken != null && !jwtToken.isEmpty() && JwtUtil.validateToken(jwtToken)) {
            try {
                //token可用
                Claims claims = JwtUtil.parseToken(jwtToken);
                String userName = claims.getSubject();
                UserDetails user = userDetailsService.loadUserByUsername(userName);
                if (user != null) {
                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } else {
            log.warn("token is null or empty or out of time, probably user is not log in !");
        }
        filterChain.doFilter(request, response);//继续过滤
    }

}
